<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.db.*,com.tianxiabuyi.model.*,com.tianxiabuyi.util.*"%>
<%@ page import="org.jsoup.Jsoup,org.jsoup.nodes.Element,org.jsoup.select.Elements"%>
<%@ page import="com.google.gson.reflect.TypeToken"%>
<%@ page import="org.dom4j.*"%>
<%!
	Message survey() {
		return survey(1,1,0);
	}

	// 准备问卷
	Message survey(Integer hospital, Integer category, Integer num) {
		Message msg = new Message();
		if (num == 0)
			num = 1;
		List<Survey> list = QBuilder.db("basedb").queryHql("from Survey where id=" + num);
		Map<String, Object> surveyMap = new HashMap<String, Object>();
		List<Map<String, Object>> quests = new ArrayList<Map<String, Object>>(); // 问题列表
		if (list.size() == 0) { // 问卷不存在
			msg.setErrcode(40001);
			msg.setErrmsg("问卷不存在");
			return msg;
		}

		// 问卷标题和id
		Survey survey = list.get(0);
		String title = survey.getTitle();
		Integer id = survey.getId();
		surveyMap.put("title", title);
		surveyMap.put("id", id);

		// 查询该问卷中所有问题
		List<SurveyQuestion> questList = QBuilder.db("basedb").queryHql("from SurveyQuestion where status=1 and surveyId="+id + "order by showOrder asc");
		// 所有问题id
		String questIds = "-1,";
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			Integer questId = quest.getId();
			questIds += questId + ",";
		}
		questIds = questIds.substring(0, questIds.length() - 1);

		// 根据问题id查出问题选项
		Map<Integer, List<Map<String, Object>>> questIdMap = new HashMap<Integer, List<Map<String, Object>>>(); // 问题和问题选项集合
		List<SurveyOptions> optionList = QBuilder.db("basedb").queryHql("from SurveyOptions where status=1 and questId in(" + questIds + ") order by showOrder asc");
		for (int i = 0; i < optionList.size(); i++) {
			SurveyOptions option = optionList.get(i);
			String content = option.getContent();
			Integer optionId = option.getId();
			Integer questId = option.getQuestId();
			List<Map<String, Object>> options = questIdMap.get(questId);
			if (null == options) {
				options = new ArrayList<Map<String, Object>>();
			}
			Map<String, Object> anOption = new HashMap<String, Object>();
			anOption.put("content", content);
			anOption.put("option_id", optionId);
			options.add(anOption);
			questIdMap.put(questId, options);
		}

		// 问题选项加到对应的问题中
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			String questTitle = quest.getTitle();
			Integer questId = quest.getId();
			Integer type = quest.getType();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("options", questIdMap.get(questId));
			quests.add(aQuest);
		}

		surveyMap.put("quests", quests);
		msg.put("survey", surveyMap);
		return msg;
	}

	// 准备问卷
	public Message survey(Map<String, String> parameters) {
		Message msg = new Message();
		int id = Tools.getInt(parameters.get("id") + "", -9999);
		List<Survey> surveys = QBuilder.db("basedb").queryHql("from Survey where id = " + id);
		if (surveys.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg;
		}
		Map<String, Object> surveyMap = new HashMap<String, Object>();
		Survey survey = surveys.get(0);
		String title = survey.getTitle();
		id = survey.getId();
		surveyMap.put("title", title);
		surveyMap.put("id", id);
		// 查询副标题
		List<SurveyQuestion> questList = QBuilder.db("basedb").queryHql("from SurveyQuestion where status = " + STATUS_ENABLE + " and surveyId = "+ id + " order by showOrder asc");
		Iterator<SurveyQuestion> it = questList.iterator();
		List<SurveyQuestion> titles = new ArrayList<SurveyQuestion>();
		List<SurveyQuestion> mulInputs = new ArrayList<SurveyQuestion>();
		String questIds = "-1";
		while (it.hasNext()) {
			SurveyQuestion sq = it.next();
			if (sq.getType() == SURVEY_QUESTION_TYPE_PARENT) {
				// 副标题
				titles.add(sq);
				it.remove();
			} else if (sq.getType() == SURVEY_QUESTION_TYPE_MUTILINPUT) {
				// 多重填空的题目
				mulInputs.add(sq);
				it.remove();
			} else {
				// 问题
				questIds += ("," + sq.getId());
			}
		}
		// 根据问题id查出问题选项
		Map<Integer, List<Map<String, Object>>> questIdMap = new HashMap<Integer, List<Map<String, Object>>>(); // 问题和问题选项集合
		List<SurveyOptions> optionList = QBuilder.db("basedb").queryHql("from SurveyOptions where status = " + STATUS_ENABLE + " and questId in(" + questIds + ") order by showOrder asc");
		for (int i = 0; i < optionList.size(); i++) {
			SurveyOptions option = optionList.get(i);
			String content = option.getContent();
			Integer optionId = option.getId();
			Integer questId = option.getQuestId();
			List<Map<String, Object>> options = questIdMap.get(questId);
			if (null == options) {
				options = new ArrayList<Map<String, Object>>();
			}
			Map<String, Object> anOption = new HashMap<String, Object>();
			anOption.put("content", content);
			anOption.put("option_id", optionId);
			anOption.put("score", option.getScore());
			options.add(anOption);
			questIdMap.put(questId, options);
		}
		// 问题选项加到对应的问题中
		LinkedList<Map<String, Object>> quests = new LinkedList<Map<String, Object>>(); // 问题列表
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion quest = questList.get(i);
			String questTitle = quest.getTitle();
			Integer questId = quest.getId();
			Integer type = quest.getType();
			Integer parentId = quest.getParentId();
			Integer necessary = quest.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("options", questIdMap.get(questId));
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", quest.getShowOrder());
			quests.add(aQuest);
		}
		// 把多重填空子题目放入大标题中
		LinkedList<Map<String, Object>> dest = new LinkedList<Map<String, Object>>();
		dest.addAll(quests);
		for (int i = 0; i < mulInputs.size(); i++) {
			SurveyQuestion sq = mulInputs.get(i);
			String questTitle = sq.getTitle();
			Integer questId = sq.getId();
			Integer type = sq.getType();
			Integer parentId = sq.getParentId();
			Integer necessary = sq.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", sq.getShowOrder());
			dest.addFirst(aQuest);
			Iterator<Map<String, Object>> itor = quests.iterator();
			while (itor.hasNext()) {
				Map<String, Object> map = itor.next();
				Integer sqId = (Integer)map.get("parent_id");
				if (questId.equals(sqId)) {
					List<Map<String, Object>> childList = (List<Map<String, Object>>)aQuest.get("multils");
					if (childList == null) {
						childList = new ArrayList<Map<String, Object>>();
						aQuest.put("multils", childList);
					}
					childList.add(map);
					itor.remove();
					dest.remove(map);
				}
			}
		}
		// 根据showorder排序
		quests.clear();
		quests.addAll(dest);
		/* Collections.sort(quests, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				return Tools.getDesc(o1.get("show_order"), "0").compareTo(Tools.getDesc(o2.get("show_order"), "0"));
			}
		}); */
		// 问题加入大分类
		dest.clear();
		dest.addAll(quests);
		for (int i = 0; i < titles.size(); i++) {
			SurveyQuestion sq = titles.get(i);
			String questTitle = sq.getTitle();
			Integer questId = sq.getId();
			Integer type = sq.getType();
			Integer parentId = sq.getParentId();
			Integer necessary = sq.getNecessary();
			Map<String, Object> aQuest = new HashMap<String, Object>();
			aQuest.put("title", questTitle);
			aQuest.put("quest_id", questId);
			aQuest.put("type", type);
			aQuest.put("parent_id", parentId);
			aQuest.put("necessary", necessary);
			aQuest.put("show_order", sq.getShowOrder());
			dest.addFirst(aQuest);
			Iterator<Map<String, Object>> itor = quests.iterator();
			while (itor.hasNext()) {
				Map<String, Object> map = itor.next();
				Integer sqId = (Integer)map.get("parent_id");
				if (questId.equals(sqId)) {
					List<Map<String, Object>> childList = (List<Map<String, Object>>)aQuest.get("quests");
					if (childList == null) {
						childList = new ArrayList<Map<String, Object>>();
						aQuest.put("quests", childList);
					}
					childList.add(map);
					itor.remove();
					dest.remove(map);
				}
			}
		}
		Collections.sort(dest, new Comparator<Map<String, Object>>() {

			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				return Tools.getInt(o1.get("show_order") + "", 0).compareTo(Tools.getInt(o2.get("show_order")+"", 0));
			}
		});
		surveyMap.put("quests", dest);
		msg.put("survey", surveyMap);
		return msg;
	}

	// 创建问卷
	Message createSurvey(String json) {
		Survey survey = Survey.fromJson(json, Survey.class);
		// 创建前的验证
		Message msg = validateCreate(survey);
		Integer code = msg.getErrcode();
		if (code == 0) { // 验证通过，真正创建问卷
			msg.put("survey", create(survey));
		}
		return msg;
	}

	// 创建
	Map<String, Object> create(Survey survey) {
		// 问卷
		Survey newSurvey = new Survey();
		Integer category = Tools.getInt(Tools.getDesc(survey.getCategory(), "1"));
		Integer hospital = Tools.getInt(Tools.getDesc(survey.getHospital(), "-1"));
		Integer enable = Tools.getInt(Tools.getDesc(survey.getEnable(), "1"));
		newSurvey.setCategory(category);
		newSurvey.setHospital(hospital);
		newSurvey.setTitle(survey.getTitle());
		newSurvey.setDetail(survey.getDetail());
		newSurvey.setEnable(enable);
		Integer surveyId = (Integer)DBTools.db("basedb").addItem(newSurvey);
		List<SurveyScore> scores = survey.getScores();
		// 分段
		for (int i = 0; i < scores.size(); i++) {
			SurveyScore score = scores.get(i);
			score.setSid(surveyId);
			score.setHospital(hospital);
			score.setType(1);
		}
		DBTools.db("basedb").addItem(scores);
		// 问题
		List<SurveyQuestion> questList = survey.getQuests();
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion aQuest = questList.get(i);
			Integer questOrder = i + 1;
			insert(aQuest, questOrder, null, surveyId, hospital);
		}
		Map<String, Object> surveyMap = new HashMap<String, Object>();
		surveyMap.put("survey_id", surveyId);
		return surveyMap;
	}

	// 递归插入问题
	public void insert(SurveyQuestion aQuest, Integer questOrder, Integer questId, Integer surveyId, Integer hospital) {
		aQuest.setShowOrder(questOrder);
		aQuest.setHospital(hospital);
		aQuest.setSurveyId(surveyId);
		aQuest.setParentId(questId);
		Integer type = aQuest.getType();
		questId = (Integer)DBTools.db("basedb").addItem(aQuest);
		if (type == SURVEY_QUESTION_TYPE_PARENT || type == SURVEY_QUESTION_TYPE_MUTILINPUT) {  // 大类型问题
			List<SurveyScore> scores = aQuest.getScores();  // 插入分段
			for (int j = 0; j < scores.size(); j++) {
				SurveyScore score = scores.get(j);
				score.setSid(questId);
				score.setHospital(hospital);
				score.setType(type == SURVEY_QUESTION_TYPE_PARENT ? 2 : 3);
			}
			if (scores.size() > 0) {  // 如果有分段则插入
				DBTools.db("basedb").addItem(scores);
			}
			List<SurveyQuestion> questions = aQuest.getQuests();
			for (int j = 0; j < questions.size(); j++) {
				SurveyQuestion aQuestion = questions.get(j);
				questOrder = j + 1;
				insert(aQuestion, questOrder, questId, surveyId, hospital);
			}
		} else {
			List<SurveyOptions> optionList = aQuest.getOptions();
			if (type < SURVEY_QUESTION_TYPE_INPUT) { // 单选多选
				for (int j = 0; j < optionList.size(); j++) {
					SurveyOptions anOption = optionList.get(j);
					Integer optionOrder = j + 1;
					anOption.setShowOrder(optionOrder);
					anOption.setHospital(hospital);
					anOption.setQuestId(questId);
					DBTools.db("basedb").addItem(anOption);
				}
			} else if(type == SURVEY_QUESTION_TYPE_INPUT || type == SURVEY_QUESTION_TYPE_MUTILINPUT_CHILD) { // 填空
				SurveyOptions anOption = new SurveyOptions();
				anOption.setContent("");
				anOption.setShowOrder(1);
				anOption.setHospital(hospital);
				anOption.setQuestId(questId);
				DBTools.db("basedb").addItem(anOption);
			} else { // 打分
				SurveyOptions anOption = new SurveyOptions();
				Integer optionOrder = 1;
				anOption.setContent("");
				anOption.setShowOrder(optionOrder);
				anOption.setHospital(hospital);
				anOption.setQuestId(questId);
				DBTools.db("basedb").addItem(anOption);
			}
		}
	}

	// 创建问卷前验证
	Message validateCreate(Survey survey) {
		Message msg = new Message(0, "问卷创建成功");
		String title = Tools.getDesc(survey.getTitle(), "");
		if (title.length() < 4) {
			msg.setErrcode(40001);
			msg.setErrmsg("问卷标题太短");
			return msg;
		} else if (title.length() > 16) {
			msg.setErrcode(40001);
			msg.setErrmsg("问卷标题太长");
			return msg;
		}
		List<SurveyQuestion> questList = survey.getQuests();
		if (questList.size() == 0) { // 没有添加问题
			msg.setErrcode(40001);
			msg.setErrmsg("问卷中没有问题");
			return msg;
		}

		// 检查问题和问题中的选项
		for (int i = 0; i < questList.size(); i++) {
			SurveyQuestion aQuest = questList.get(i);
			return validate(aQuest);
		}
		return msg;
	}

	// 递归校验问题
	public Message validate(SurveyQuestion aQuest) {
		Message msg = new Message(0, "问卷创建成功");
		String questTitle = Tools.getDesc(aQuest.getTitle(), "");
		if (questTitle.length() < 4) {
			msg.setErrcode(40001);
			msg.setErrmsg("问题太短");
			return msg;
		} else if (questTitle.length() > 50) {
			msg.setErrcode(40001);
			msg.setErrmsg("问题太长");
			return msg;
		}

		Integer questType = Tools.getInt(Tools.getDesc(aQuest.getType(), "-1"), -1);
		if (questType < 0 || questType >6) { // 检查问题类型
			msg.setErrcode(40001);
			msg.setErrmsg("问题类型有误");
			return msg;
		}
		if (questType == SURVEY_QUESTION_TYPE_PARENT || questType == SURVEY_QUESTION_TYPE_MUTILINPUT) { // 大类问题与多项问题校验
			List<SurveyQuestion> questions = aQuest.getQuests();
			if (questions.size() == 0) {
				msg.setErrcode(40001);
				msg.setErrmsg("问卷中没有问题");
				return msg;
			}
			for (int i = 0; i < questions.size(); i++) {
				aQuest = questions.get(i);
				msg = validate(aQuest);
				if (msg.getErrcode() != 0)
					return msg;
			}
		} else {
			if (questType < 3 && questType > 0) { // 对于单选多选必须要有选项
				List<SurveyOptions> optionList = aQuest.getOptions();
				if (optionList.size() == 0) {
					msg.setErrcode(40001);
					msg.setErrmsg("单选多选必须要有选项");
					return msg;
				}
				// 检查选项长度
				for (int j = 0; j < optionList.size(); j++) {
					SurveyOptions anOption = optionList.get(j);
					String content = Tools.getDesc(anOption.getContent(), "");
					if (content.length() < 1) {
						msg.setErrcode(40001);
						msg.setErrmsg("选项太短");
						return msg;
					} else if (content.length() > 30) {
						msg.setErrcode(40001);
						msg.setErrmsg("选项太长");
						return msg;
					}
				}
			}
		}
		return msg;
	}


%>
